package com.yueyang.sojourn.server.service.sojourn.order;

import com.yueyang.sojourn.server.model.enums.OrderEventTypeEnum;
import com.yueyang.sojourn.server.model.po.SojournOrderEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 订单事件快照服务
 * @author andy.yang
 * @version v1
 * @summary
 * @Copyright (c) 2019, yueyang Group All Rights Reserved.
 * @since 2020/3/24
 */
@Service
public class SojournOrderEventService {
    @Resource
    SojournOrderEventMapper sojournOrderEventMapper;
    @Autowired
    private ApplicationContext context;

    /**
     * 创建订单事件快照
     * @param orderId 订单id
     * @param eventType 订单事件类型
     *
     * @return
     */
    public SojournOrderEvent addAndReturn(Long orderId, OrderEventTypeEnum eventType,Long creator){
        SojournOrderEvent event = new SojournOrderEvent(this);
        event.setType(eventType.getCode());
        event.setOrderId(orderId);
        event.setCreator(creator);
        if(sojournOrderEventMapper.insert(event) <= 0){
            throw new RuntimeException("事件快照创建失败");
        }
        context.publishEvent(event);
        return event;
    }

    /**
     * @param orderId      订单事件
     * @return
     * @author Andy.yang
     * @summary 订单事件分页查询
     * @version v1
     * @since 2020-02-19
     */
    public List<SojournOrderEvent> findByOrderId(Long orderId) {
        return sojournOrderEventMapper.findByOrderId(orderId);
    }

    /**
     * @param orderEventId      订单订单事件快照id
     * @return
     * @author Andy.yang
     * @summary 订单分页查询
     * @version v1
     * @since 2020-02-19
     */
    public SojournOrderEvent findById(Long orderEventId) {
        return sojournOrderEventMapper.selectByPrimaryKey(orderEventId);
    }
}
